
	    var db, mbServer, online;
	    var glossOverlay = "background-image: -webkit-gradient(radial, 28.5 -47, 0, 28.5 0, 700,from(rgba(255,255,255,1)), to(rgba(255,255,255,0)),color-stop(10%, rgba(255,255,255,0.2)),color-stop(10.5%, rgba(140,140,140,0.2)),color-stop(13%, rgba(140,140,140,0)),color-stop(13.7%, rgba(255,255,255,0)),color-stop(17%, rgba(255,255,255,1))), "
	    var NP = 0;
	    var NowPullingMeta = false;
			var NPDuration = 0;
			var NPElapsed = 0;
			
      function goBack(bck) {
      	
      	oldSlide = $("#curPage").val();
      	newSlide = getLastfromHistory();
      	
				if (bck == "home") {
					newSlide = "home";
					$("#curPage").val('');
					$("#search").attr('style','');
					$("#search").attr('class','selectable');

				}
				
				$("#"+newSlide).attr('class','current');
				$("#"+oldSlide).attr('style','');
				$("#"+newSlide).attr('style','');
      	
      	$("#"+oldSlide).bind('webkitAnimationEnd', function(e, info){
      		$("#"+oldSlide).attr('class','');
      		window.setTimeout(function() {
						
						if (bck == "home") {
							$("#body > div").each(function(i) {
								if ( $(this).attr("divType") == "New") {
									$(this).remove();	
								}
							});
						} else {
							$("#body > div:last").remove();	
						}
      			
					  //window.scrollBy( $('#scrollx').val()*1, $('#scrolly').val()*1);
					  
					  if (localStorage.getItem("snapTo") == "true") {

						  scrollval = $('#lir' + oldSlide);
						  if (scrollval.size() == 1) {
							  if ( scrollval.position().top > $(window).height() ) {
							  	window.scrollBy( 0, scrollval.position().top );
								}
						  }
						}

					}, 50);
      	});
      	
      	$("#"+newSlide).bind('webkitAnimationEnd', function(e, info){
      		$("#"+newSlide).attr('class','current');
      		$("#"+newSlide).css('left', '0px');
      	});

				$("#"+oldSlide).addClass("backSlideOut");
				$("#"+newSlide).addClass("backSlideIn");
				$("#curPage").val(newSlide);
				
      }
      
      
			function jumpTo(newSlide, oldSlide) {

				addToHistory(oldSlide, newSlide);
				
				window.scrollTo(0,0);
				
				$("#"+newSlide).attr('class','current');
				$("#"+oldSlide).attr('style','');
				$("#"+newSlide).attr('style','');
				
      	$("#"+oldSlide).bind('webkitAnimationEnd', function(e, info){
      		$("#"+oldSlide).attr('class','selectable');
      	});
      	
      	$("#"+oldSlide).bind('webkitAnimationStart', function(e, info){
      		$("#link"+newSlide).removeClass('active');
      	});
      	        	
      	$("#"+newSlide).bind('webkitAnimationEnd', function(e, info){
      		$("#"+newSlide).attr('class','current');
      		$("#"+newSlide).css('left', '0px');
      		setTimeout('pullMissingMeta("' + newSlide + '")', 500);
      	});
      	
				$("#"+oldSlide).addClass("divSlideOut");
				$("#"+newSlide).addClass("divSlideIn");
								
			}
			
			function pullMissingMeta(slide) {
				if (NowPullingMeta) {
					return false;
				}
				
				if (online == false) {
					return false;
				}
				
				db.transaction(function(tx) {
					NowPullingMeta = true;
					resLoop = $("#results"+slide+" li a");
					var TotElements = resLoop.size();
					resLoop.each( function( i ) {
							
							var pos = $(this).position(), win = $(window);

							if ( pos.top < win.height() + win.scrollTop() ) {
							} else { //visible
								NowPullingMeta = false;

								return false;
							}
							GUID = $(this).attr("GUID");
							
							if (pos.top > (window.scrollY-40) ) {

								if ($("#img" + GUID).attr("style") == "" ) {
									$("#img" + GUID).attr("style", glossOverlay + ' url(\'' + mbServer + '/directimage/?id='+GUID+'&imagetype=PrimaryImage&maxheight=120\');')
								}
								$("#hidimg" + GUID).attr("src", mbServer + '/directimage/?id='+GUID+'&imagetype=PrimaryImage&maxheight=120')
								
								$("#hidimg" + GUID).error(function() {
									console.log("imgarroe");
									$(this).next().attr("style", "");
								});
								
								if ($(this).attr("needsMeta") == "1" ) {
									data = get(mbServer + "item?id="+GUID+"&callback=foo");
							    if(data.Id) {
							    				if (data.ImdbRating) {
							    					imdb = data.ImdbRating
							    				} else {
							    					imdb = 0
							    				}
											  	tx.executeSql('INSERT INTO mbMeta (GUID, CustomRating, DateCreated, DateModified, ImdbRating, Overview, ProductionYear, RunningTime, Parent, chk) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)', [ data.Id, data.CustomRating, data.DateCreated, data.DateModified, imdb, data.Overview, data.ProductionYear, data.RunningTime, ''  ], function (tx, results) {
												    console.log('Worker Row inserted: ' + data.Id);
												  }, function (tx, err) {
												  	console.log('Meta Item Exists ' +  data.Id + ': ' + err.message);
	
												  });
												$("#link"+data.Id).attr("needsMeta", "0");
												$("#link"+data.Id).append('<span class="stars' + getStarsClass(data.ImdbRating) + '"></span>')
												$("#lir"+data.Id).attr("class", "forward");
							    }
								}
								
							}

					});
					NowPullingMeta = false;
				});
			}	
			
			function keyupSearch(term) {
				term = jQuery.trim( term );
				if (term != "" && term.length > 2) {
					setTimeout("doSearch('" + term + "')", 500)
				} else {
					$("#resultssearch").html("");
				}
			}
			function doSearch(term) {

				if ($("#searchbox").val() == term ) { 
					term = $("#searchbox").val();
					term = jQuery.trim( term )
					terms = term.split(" ")
					term = " 1=1 "
					for (i = 0; i < terms.length; i++) {
						if (terms[i] != "") {
							term = term + " AND mbItems.Name Like \"%" + terms[i] + "%\" "
						}
					}

					db.transaction(function(tx) {
								tx.executeSql('SELECT mbItems.*, mbMeta.GUID as Meta, mbMeta.ImdbRating FROM mbItems LEFT JOIN mbMeta ON mbItems.GUID = mbMeta.GUID WHERE (' + term + ') AND (mbItems.TypeName="Movie" OR mbItems.TypeName="Episode" OR mbItems.TypeName="Folder") Order By mbItems.Name LIMIT 50', [ ], function (tx, rs) {
							  	var len = rs.rows.length, i;
							  	$("#resultssearch").html("");
							  	for (i = 0; i < len; i++) {
							  							  		
								    rst = rs.rows.item(i);
										needMeta = 0;
										cls="forward"
										stars=""
										if (rst["TypeName"] == "Movie" || rst["TypeName"] == "Episode") {
											if (rst["Meta"] == null) {
												needMeta = 1;	
												cls="loading"
											} else {
												stars = '<span class="stars' + getStarsClass(rst["ImdbRating"]) + '"></span>'
											}
										}
										if (online == true) {
											//Pic = glossOverlay + ' url(\'' + mbServer + '/directimage/?id='+rst["GUID"] +'&imagetype=PrimaryImage&maxheight=120\');'
											Pic = glossOverlay + ' url(\'/MediaBrowserService/web/image/icon.png\');'
										} else {
											Pic = glossOverlay + ' url(\'/MediaBrowserService/web/image/icon.png\');'
										}
										$("#resultssearch").append('<li class="'+cls+'" id="lir'+ rst["GUID"] +'" GUID="'+ rst["GUID"] +'"><div class="mbIcon" style="" id="img'+ rst["GUID"] +'" GUID="'+ rst["GUID"] +'">&nbsp;</div><a id="link'+ rst["GUID"] +'" needsMeta="'+needMeta+'" class="" GUID="'+ rst["GUID"] +'" ParentGUID="search" name="'+ rst["Name"] +'" typeName="'+ rst["TypeName"] +'" level="'+ rst["Type"] +'" href="#'+ rst["GUID"] +'" onclick="getFolder(this);">' + rst["Name"] + stars +'</a></li>')		
								  }
								  setTimeout('pullMissingMeta("search")', 500);

							  }, function (tx, err) {
							  	console.log("could not find rows for: " + term + " " + err.message);
							  });

					});
					
				}
				
			}
			
			function markAsReady(GUID, Rating) {
				$("#link"+GUID).attr("needsMeta", "0");
				$("#link"+GUID).append('<span class="stars' + getStarsClass(Rating) + '"></span>')
				$("#lir"+GUID).attr("class", "forward");
			}
				
				function addToHistory(oldP, newP) {
					var curHist = $("#curHistory").val();
					$("#curHistory").val( curHist + "|" + oldP  )
					$("#curPage").val(newP);
				}
        
        function getLastfromHistory() {
        	var curHist = $("#curHistory").val();
        	var arr = curHist.split("|");       	
        	var lastPage = "";
        	var newHist = "";
        	
					for(var i=arr.length-1; i>=0; i--) {
						if (arr[i] != "" && lastPage == "") {
							lastPage = arr[i];
						} else {
							newHist = arr[i] + "|" + newHist;	
						}
						
					}
					newHist = newHist.substr(0, newHist.length-1);
					$("#curHistory").val(newHist);
					return lastPage;
        }

        

				
	      $(document).ready(function() {
	      	mbServer = window.location.href;
	    		mbServer = mbServer.substr(0, mbServer.indexOf("web/"));
		      	if (navigator.userAgent.indexOf("AppleWebKit") > -1 && navigator.userAgent.indexOf("Android") == -1 ) {
		      		$('head').append('<link rel="stylesheet" href="/MediaBrowserService/web/css/iphone.css" type="text/css" />');
		      	}
					loadSettings();
	    		startUp();  		
	    		
	      });
	      


	      function startUp(force) {
	      	
	      	
					$("#search").bind('touchend', function(){ setTimeout('pullMissingMeta("search")', 500); });	
					
	      	$("#cuboid-buttons div").bind("touchend", function(event) {  
	      				event.preventDefault();
		        		$("#cuboid-buttons div").attr("class", "swipeButtons");
		        		document.getElementById('demo-cuboid').getElementsByTagName('div')[0].className = 'cube to' + $(this).attr("cubeto");
		        		$(this).attr("class", "swipeButtonsH");
		      });
		      
		      
		      
	      	$("#seekbarContainer").bind("touchstart", function(event) {  
	      		if (NPDuration > 0) {
	      			event.preventDefault();
							clearInterval(NP);
						}
					});
					
	      	$("#seekbarContainer").bind("touchend", function(event) {  
	      		if (NPDuration > 0) {
	      			event.preventDefault();
					    var max = $("#sliderbar").width();
					    var x = $("#sliderh").width();
					    if (x > max) {
					    	x = max;
					    }
					    
					    var seekTo = Math.floor( NPDuration * (x/max) );
					    console.log("Seconds to seek: " + seekTo)
							data = get(mbServer + "/seek?duration="+seekTo+"&callback=foo");
							queryNP();
	      			NP = setInterval("queryNP()", 3000);
	      			data = get(mbServer + "/command?type=Play&callback=foo");
	      		}
					});
					
	      	$("#seekbarContainer").bind("touchmove", function(event) {  
		      		if (NPDuration > 0) {
		      			event.preventDefault();
								var e = event.originalEvent;
						    var touch = e.touches[0]; 

						    var max = $("#sliderbar").width();
						    var x = touch.pageX;
						    if (x > max) {
						    	x = max;
						    }
						    $("#seekto").attr("style", "left: " + (x-10) + "px");
						    $("#sliderh").attr("style", "width: " + ((x/max)*100) + "%");
						    $("#timespanleft").html();
						    $("#timespanright").html();
						    
						    var seekTo = Math.floor( NPDuration * (x/max) );
						    
						    $("#timespanright").html( "-" + hms2(NPDuration-seekTo) );
          	    $("#timespanleft").html( hms2(seekTo) );
          	
							}
					});
					
					

	      	$("#info").html("Loading Data...");
	      	online = false;
	      	try {
						$.ajax({
						    url: mbServer + "Startup?callback=foo",
						    timeout: 5000,
						    success: function (data, text) {
									
									if (data) {
										online = true;
										console.log("got data")
										if ( checkDB() == true ) {
											if (localStorage.getItem("StartupScan") == "true" || force == true ) {
												buildDB();
												refreshAll();
											}
											showRoot();	
										} else {
											console.log("Error Creating Database");
										}
									} else {
										if ( checkDB() == true ) {
											online = false;
											showRoot();	
											console.log("offline")
										} else {
											console.log("Error Creating Database");
										}
									}
	
						    },
						    error: function (request, status, error) {
						       online = false;
						       if ( checkDB() == true ) {
										showRoot();	
									}
						    }
						});
	      	} catch (E) {
			       online = false;
			       if ( checkDB() == true ) {
							showRoot();	
						}
	      	}

	      }
	      
	      function doAlert(msg, persists) {
	      	$("#loader").html(msg);
	      	$("#loader").show();
	      	if (persists == false) {
	      		$("#loader").delay(3000).fadeOut(500);
	      	}
	      }
            
				function checkDB() {
					try {
						db = openDatabase("mB", "0.1", "Media broswer cache", 200000);	
						$("#info").html("Loading Data...");
						return true;
					} catch(e) {
						$("#info").html("Error creating database");
						return false;
					}
				}
				
				function buildDB(KillAll) {
					db = openDatabase("mB", "0.1", "Media broswer cache", 200000);	
					$("#homeCategories").remove();
				  db.transaction(function(tx) {
				  	
			  		tx.executeSql('DROP TABLE mbItems',[], function (tx, results) {
					    console.log('DB Cleared');
					  }, function (tx, err) {
					  	console.log(err.message);
					  });

					  if (KillAll == true) {
					  	
					  	tx.executeSql('DROP TABLE mbMeta',[], function (tx, results) {
						    console.log('DB Cleared');
						  }, function (tx, err) {
						  	console.log(err.message);
						  });

					  }

						tx.executeSql('CREATE TABLE IF NOT EXISTS mbItems (GUID TEXT unique PRIMARY KEY, Type TEXT, TypeName TEXT, Name TEXT, DT INTEGER, Parent TEXT, chk INTEGER, Total INTEGER)',[], function (tx, results) {
					    console.log('table validated');
					    return true;
					  }, function (tx, err) {
					  	console.log('table exists');
					  	return false;
					  });
					  
						tx.executeSql('CREATE TABLE IF NOT EXISTS mbMeta (GUID TEXT unique PRIMARY KEY, CustomRating TEXT, DateCreated TEXT, DateModified TEXT, ImdbRating INTEGER, Overview TEXT, ProductionYear TEXT, RunningTime TEXT, Parent TEXT, chk INTEGER)',[], function (tx, results) {
					    console.log('table validated');
					    return true;
					  }, function (tx, err) {
					  	console.log('table exists');
					  	return false;
					  });
					  					  
				  });
				}
			
				function showResults(GUID, pGUID, txt) {
					db.transaction(function(tx) {
							if ( $("#" + GUID).size() == 0 ) {
								tx.executeSql('SELECT mbItems.*, mbMeta.GUID as Meta, mbMeta.ImdbRating FROM mbItems LEFT JOIN mbMeta ON mbItems.GUID = mbMeta.GUID WHERE mbItems.Parent = ? Order By ' + localStorage.getItem("Sort") + ' LIMIT ' + ((localStorage.getItem("perPage")*1)+1), [ GUID ], function (tx, rst) {
							  	console.log("Rows Found: " + rst.rows.length + " for " + GUID);
							  	var len = rst.rows.length, i;
							  	
							  	if (len <= (localStorage.getItem("perPage")*1) ) {
							  		var to = len
							  	} else {
							  		var to = (len-1)
							  	}
							  	
							  	for (i = 0; i < to; i++) {
							  		if (i == 0) {
							  			createTarget(GUID, txt, rst.rows.item(i).TypeName );
							  		}
							  		
								    createLI( rst.rows.item(i) );
								  }
								  
								  if (len > (localStorage.getItem("perPage")*1) ) {
								  	createMOAR(GUID, 2);
								  }
								  jumpTo(GUID, pGUID);
							  }, function (tx, err) {
							  	console.log("could not find rows for: " + GUID + " " + err.message);
							  });
							} else {
								jumpTo(GUID, pGUID);
							}
					});
				}
				
				function createMOAR(GUID, curPage) {
					$("#results" + GUID).append('<li class="forward"><a href="javascript:void(0)" id="linkMOAR" style="padding-top: 26px; padding-bottom: 0px" style="padding-top: 5px" onclick="doMoar(' + curPage + ', \'' + GUID + '\', this);">Show ' + localStorage.getItem("perPage") + ' more</a></li>')
				}
				
				function doMoar(curPage, GUID, moar) {
					db.transaction(function(tx) {
							offs3t = (curPage * (localStorage.getItem("perPage")*1) );
							tx.executeSql('SELECT mbItems.*, mbMeta.GUID as Meta, mbMeta.ImdbRating FROM mbItems LEFT JOIN mbMeta ON mbItems.GUID = mbMeta.GUID WHERE mbItems.Parent = ? Order By ' + localStorage.getItem("Sort") + ' LIMIT ' + (localStorage.getItem("perPage")*1+1) + ' OFFSET '+ offs3t, [ GUID ], function (tx, rst) {
						  //tx.executeSql('SELECT * FROM mbItems WHERE Parent = ? Order By ' + localStorage.getItem("Sort") + ' LIMIT 50', [ GUID ], function (tx, rst) {
						  	console.log("Rows Found: " + rst.rows.length + " for " + GUID);
								curPage = curPage + 1;
						  	var len = rst.rows.length, i;
						  	if (len <= (localStorage.getItem("perPage")*1) ) {
						  		var to = len
						  	} else {
						  		var to = (len-1)
						  	}
						  	for (i = 0; i < to; i++) {
							    createLI( rst.rows.item(i) );
							  }
							  
							  $(moar).parent().remove();
							  
							  if (len > (localStorage.getItem("perPage")*1) ) {
							  	createMOAR(GUID, curPage);
							  }
							  

						  }, function (tx, err) {
						  	console.log("could not find rows for: " + GUID + " " + err.message);
						  });

					});
				}
				
				function showMeta(GUID, pGUID, txt, typeName) {

					db.transaction(function(tx) {
						if ( $("#" + GUID).size() == 0 ) {
						  tx.executeSql('SELECT mbMeta.*, mbItems.TypeName from mbMeta Inner JOIN mbItems ON mbMeta.GUID = mbItems.GUID WHERE mbMeta.GUID = ?', [ GUID ], function (tx, rst) {
						  	console.log("Rows Found: " + rst.rows.length + " for " + GUID);
						  	if (rst.rows.length > 0) {
						  		createTarget(GUID, txt);
						  		
						  		pullImgFor = GUID
						  		if (typeName != "Movie") {
						  			pullImgFor = pGUID
						  		}
						  				
									img = "";
									if (online == true) {
										img = mbServer + '/directimage/?id='+pullImgFor+'&imagetype=PrimaryImage&maxwidth=120'		
										if (rst.rows.item(0).TypeName == "Movie") {
											bkdrop = mbServer + '/directimage/?id='+GUID+'&imagetype=BackdropImage&maxwidth=300'								
										} else {
											bkdrop = mbServer + '/directimage/?id='+GUID+'&imagetype=PrimaryImage&maxwidth=300'								
										}
										
									} else {
										img = "/MediaBrowserService/web/image/Movie.png"										
										bkdrop = ''
									}
									
									var boxcover = document.createElement("img");
									boxcover.setAttribute("src", img)
									$(boxcover).error(function(){
										$(this).attr("src", "/MediaBrowserService/web/image/Movie.png");
									});

									var backdrop = document.createElement("img");
									backdrop.setAttribute("src", bkdrop)
									$(backdrop).error(function(){
										$(this).parent().hide();
									});
													 
									$("#" +GUID).append('<div class="mediaHeading"><div class="largeBoxCover" style="" id="cover'+ pullImgFor +'" GUID="'+ pullImgFor +'"></div><div class="mediaTitle"><span class="title">' +txt + ' ' + cleanYear(rst.rows.item(0).ProductionYear) + '</span>' + cleanRuntime(rst.rows.item(0).RunningTime) + '' + cleanImdb(rst.rows.item(0).ImdbRating) + '<span class="stars' + getStarsClass(rst.rows.item(0).ImdbRating) + '"></span><span style="padding-top: 15px;" id="playcontrols"><a class="watchVideo" href="javascript:void(0)" GUID="' + GUID + '" onclick="play(this)">Play Title</a><span></div></div> <div class="mediaOverview"><span class="title">' +txt + '</span>' + correctVal(rst.rows.item(0).Overview) + '<span class="title" style="padding-top: 20px">Trailer (if available): </span></div><div class="mediaBackdrop" id="backdrop'+ pullImgFor +'" GUID="'+ pullImgFor +'"></div>')	
							    jumpTo(GUID, pGUID);
							    
							    $('#cover'+ pullImgFor).append(boxcover);
							    $('#backdrop'+ pullImgFor).append(backdrop);
							    if (typeName == "Movie" && localStorage.getItem("imdb")=="true" ) {
							    	var t=setTimeout('getTrailer("'+pullImgFor+'","' + GUID + '");', 1500);
							    }
							  }
							  
						  }, function (tx, err) {
						  	console.log("could not find rows for: " + parentGUID + " " + err.message);
						  });
						} else {
							jumpTo(GUID, pGUID);
						}
					});
				}
				
				function cleanYear(val) {
					if (val == "null" || val == null) {
						return "";
					} else {
						if ( isNumeric(val) == false ) {
							return "";
						}
					}
					if (n==0) {
						return "";
					}else{
						return "("+n+")";	
					}
				}
				function cleanRuntime(val) {
					if (val == "null" || val == null || isNumeric(val) == false) {
						return "";
					} else {
						try {
							n = val*1;
						} catch(x) {
							return "";
						}
					}
					if (n<=0) {
						return "";
					}else{
						return "<span>"+n+" mins<span>";
					}
				}
				function cleanImdb(val) {
					if (val == "null" || val == null) {
						return "";
					} else {
						if ( isNumeric(val) == false ) {
							return "";
						}
					}
					if (n<=0) {
						return "";
					}else{
						return "<span>IMDB Rating: "+n+"<span>";	
					}
				}
				function correctInt(val) {
					if (val == "null" || val == null || isNumeric(val) == false) {
						n = 0;
					} else {
						try {
							n = val*1;
						} catch(x) {
							n = 0;
						}
					}
					return n;
				}
				
				function getStarsClass(val) {
					if (val == "null" || val == null || isNumeric(val) == false) {
						n = 0;
					} else {
						try {
							n = Math.round( (val*1) /2);
						} catch(x) {
							n = 0;
						}
					}
					return n;
				}
				
				function correctVal(val) {
					if (val == "null" || val == null) {
						n = "";
					} else {
						n = val;
					}
					return n;
				}
					
			function playthis() {
				GUID = $("#curPage").val();
		  	if (online == true) {
			  	data = get(mbServer + "/play?id="+GUID+"&callback=foo");
			    if(data) {
						if(data == true ) {
							closeSlide('picklist');
						} else {
							alert("Error Playing Title")
						}
	        } else {
	        	alert("Error Playing Title")
	        }
		  	} else {
		  		alert("Cannot play in offline mode");
		  	}
			}
			
			function streamthis() {
		  	$("#play1").hide();
		  	$("#play2").show();
		  }
		  
			function dostream(GUID, Fname) {
		  	if (online == true) {
		  			$("#play2").html("<p>&nbsp;</p><p style='text-align:center;width:100%;height:200px'>Loading Streaming Video...</p><p>&nbsp;</p>");
						$.ajax({
						    url: mbServer + "/stream?id="+GUID+"&fname="+Fname+"&url="+mbServer,
						    timeout: 15000,
						    success: function (resp) {
						    	if (resp == "true" || resp == true) {
						    		
											console.log("stream found");
											var video = document.createElement("video");
											video.setAttribute("src", mbServer + "/web/stream/stream.m3u8");
											video.setAttribute("id", "myVideo");
											video.setAttribute("height", "300px");
											video.setAttribute("width", "100%");
											video.setAttribute("autoplay", "true");
											video.setAttribute("controls", "");
											$("#play2").html("");
											$("#play2").append(video);																						
						    			//window.location.href = mbServer + "/web/stream/stream.m3u8"
						    	} else {
						    		$("#play2").html("<p>&nbsp;</p><p>Could not load video for streaming.</p><p>&nbsp;</p>");
						    	}
						    }
						});
		  	} else {
		  		alert("Cannot play in offline mode");
		  	}
			}
			
			function closePlay() {
				GUID = $("#curPage").val();
				closeSlide('picklist');
				$.ajax({
				    url: mbServer + "/streamItems?id=" + GUID + "&callback=foo",
				    timeout: 5000,
				    success: function (resp) {
				    }
				});
			}
		  function play(pbutton) {
		  	
		  	GUID = $(pbutton).attr("GUID");
		  	$("#play1").show();
		  	$("#play2").hide();
		  	$("#play2").html("<p>&nbsp;</p><p style='text-align:center'>Live streaming is very beta, and may not work on all videos.<br>Choose a file from the list below.<br></p><br>");
		  	
				$.ajax({
				    url: mbServer + "/streamItems?id=" + GUID + "&callback=foo",
				    timeout: 5000,
				    success: function (resp) {
				    	arr = resp.split("||");
				    	for(i = 0; i < arr.length; i++){
				    		if (arr[i] != "") {
				    			$("#play2").append("<p><a class='whiteButton' href='javascript:void(0)' onclick='dostream(\"" + GUID + "\",\"" + arr[i] + "\")'>" + arr[i] + "</a></p><br>");
				    		}
							}
				    }
				});
		  	slideload('picklist');
		  	return;

		  }
			function clearHLite(item)  {
				setTimeout(function() {
									$(item).attr("class", "")
				 }, 500);
			}
			function getFolder(item){
						GUID = $(item).attr("GUID");
						parentGUID = $(item).attr("ParentGUID");
						txt = $(item).attr("name");
						typeName = $(item).attr("typeName");
						level = $(item).attr("level");
						
						if ( $("#lir"+GUID).size() != 0 ) {
							if ( $("#lir"+GUID).hasClass("forward") == false  ) {
								if (online == true) {
									alert("This item has no metadata, or it has yet to pulled from the server");	
								} else {
									alert("Metadata for this item was not pulled from the server, and cannot be retrieved in offline mode");	
								}
								
								return false;
							}
						}
						$(item).addClass("active");	
						
						if (typeName == "Movie" || typeName == "Episode" || typeName == "Song") {
							db.transaction(function(tx) {
								  tx.executeSql('SELECT * FROM mbMeta WHERE GUID = ? LIMIT 1', [ GUID ], function (tx, rst) {
											if (rst.rows.length != 0) {
												showMeta(GUID, parentGUID, txt, typeName);
											}
								  }, function (tx, err) {
								  	console.log("could not find rows for: " + parentGUID + " " + err.message);
								  });
							 });
						} else {
							//Attempt to pull from DB b4 JSON.
							
							db.transaction(function(tx) {
								  tx.executeSql('SELECT Parent FROM mbItems WHERE Parent = ? LIMIT 1', [ GUID ], function (tx, rst) {
											if (rst.rows.length != 0) {
												showResults(GUID, parentGUID, txt);
											} 
								  }, function (tx, err) {
								  	console.log("could not find rows for: " + parentGUID + " " + err.message);
								  });
							 });
						}

		  }
		  
			function getDirectories(){
	        $.getJSON(mbServer + "Startup?callback=foo",
	        function(data){
	          if(data.Id){
	          	addItem(data);
							showResults(data.Id);
	          } else {
	            alert("Error Contacting mbServer");
	          }
	        }
	      );   
	   }
	   
		function showRoot() { 
			
				$("#homeCategories").remove();
				
				db.transaction(function(tx) {
				  tx.executeSql('SELECT * FROM mbItems WHERE TypeName = "Root" Order By Name ASC', [],function (tx, rst) {
				  	console.log("Rows Found: " + rst.rows.length + " for Root");
				  	
				  	var len = rst.rows.length, i;
			  		if (len!=0) {
			  			if (online == true) {
			  				$("#info").html("Loaded Successfully")	
			  			} else {
			  				$("#info").attr("class", "offline");
			  				$("#info").html("Loaded Successfully: OFFLINE MODE")
			  			}
			  			
				  		$('<ul class="rounded" id="homeCategories"></ul>').insertAfter($('#info'));		
					  	for (i = 0; i < len; i++) {
					  		createLI( rst.rows.item(i), true )
					  		GUID = rst.rows.item(i).GUID
					  		tx.executeSql('SELECT Parent, Count(*) as T FROM mbItems WHERE Parent = ?', [ GUID ],function (tx, c) {
					  			$("#link"+c.rows.item(0).Parent).append('<small class="counter">' + c.rows.item(0).T + '</small>')
					  		});
						  }
				  	}
				  	
				  }, function (tx, err) {
				  	console.log("could not find root rows " + err.message);
				  });
				});
   	}

		function createTarget(GUID, title, typeName) {
					lastSection = ""
					$("#body").append('<div id="'+ GUID +'" class="" divType="New"></div>');

					$("#"+GUID).unbind('touchend');
					$("#"+GUID).bind('touchend', function(){ setTimeout('pullMissingMeta("' + GUID + '")', 500); });	
					
					$("#"+GUID).append('<div class="toolbar"><h1>'+title+'</h1><a class="homebutton" onclick="goBack(\'home\')"><img alt="home" src="/MediaBrowserService/web/image/home.png"></a><a class="back" onclick="goBack()">Back</a></div>');

					if (typeName == "Season" && online == true) {
						$("#"+GUID).append('<p id="banner'+GUID+'" style="width: 100%; height:80px;"></p>')
						
						var banner = document.createElement("img");
						banner.setAttribute("src", '/MediaBrowserService/directimage/?id='+GUID+'&imagetype=BannerImage&maxwidth=320')
						banner.setAttribute("style", "width: 100%; height: 100%")
						$(banner).error(function(){
							$(this).parent().hide();
						});
						$('#banner'+ GUID).append(banner);
					}
					$("#"+GUID).append('<ul id="results'+ GUID +'" class="edgetoedge"></ul>')
		    	
		}
		
		var lastSection;
		var today=new Date();
		
		function createLI(rst, root) {
					
			if (root == true) {
				$("#homeCategories").append('<li class="arrow"><img src="/MediaBrowserService/web/image/refresh.png" onclick="refreshOne(\''+ rst["GUID"] +'\')" style="float:left"><a id="link'+ rst["GUID"] +'" GUID="'+ rst["GUID"] +'" ParentGUID="'+ rst["Parent"] +'" name="'+ rst["Name"] +'" typeName="'+ rst["TypeName"] +'" level="'+ rst["Type"] +'" href="#'+ rst["GUID"] +'" onclick="getFolder(this)">' + rst["Name"] + '</a> </li>')
			} else {

				if ( localStorage.getItem("Sort") == "DT DESC" ) {
					var t = rst["DT"].substr( rst["DT"].indexOf("(")+1 );
					t = t.substr( 0, t.indexOf("-") );
					var myDate = new Date( t *1);
					var daysDiff = (myDate.valueOf() - today.valueOf());
  				daysDiff = Math.floor(Math.abs((((daysDiff  / 1000) / 60) / 60) / 24));
  				if (daysDiff == 0) {
  					curSection = "Today"
  				} else if (daysDiff == 1) {
  					curSection = "Yesterday"
  				} else if (daysDiff >= 2 && daysDiff < 7) {
  					curSection = "This Week"
					} else if (daysDiff >= 7 && daysDiff < 30) {
  					curSection = "This Month"
					} else if (daysDiff >= 30 && daysDiff < 60) {
  					curSection = "Last Month"
					} else if (daysDiff >= 60 && daysDiff < 90) {
						curSection = "Over 2 Months Old"
					} else if (daysDiff >= 90 && daysDiff < 365) {
						curSection = "Over 3 Months Old"
					} else if (daysDiff >= 365) {
						curSection = "Older than a Year"
					}
					
				} else {
					var curSection = rst["Name"].substr(0,1);
				}
				
				if (curSection != lastSection) {
					$("#results" + rst["Parent"]).append('<li class="sep">'+curSection+'</li>')
					lastSection = curSection;
				}
				
				needMeta = 0;
				cls="forward"
				stars=""
				if (rst["TypeName"] == "Movie" || rst["TypeName"] == "Episode" || rst["TypeName"] == "Song") {
					if (rst["Meta"] == null) {
						needMeta = 1;	
						cls="loading"
					} else {
						stars = '<span class="stars' + getStarsClass(rst["ImdbRating"]) + '"></span>'
					}
				}
				if (online == true) {
					//Pic = glossOverlay + ' url(\'' + mbServer + '/directimage/?id='+rst["GUID"] +'&imagetype=PrimaryImage&maxheight=120\');'
					Pic = glossOverlay + ' url(\'/MediaBrowserService/web/image/icon.png\');'
				} else {
					Pic = glossOverlay + ' url(\'/MediaBrowserService/web/image/icon.png\');'
				}

				$("#results" + rst["Parent"]).append('<li class="'+cls+'" id="lir'+ rst["GUID"] +'" GUID="'+ rst["GUID"] +'"><img style="display:none" src="" id="hidimg' + rst["GUID"] + '"  /><div class="mbIcon" style="" id="img'+ rst["GUID"] +'" GUID="'+ rst["GUID"] +'">&nbsp;</div><a id="link'+ rst["GUID"] +'" needsMeta="'+needMeta+'" class="" GUID="'+ rst["GUID"] +'" ParentGUID="'+ rst["Parent"] +'" name="'+ rst["Name"] +'" typeName="'+ rst["TypeName"] +'" level="'+ rst["Type"] +'" href="#'+ rst["GUID"] +'" onclick="getFolder(this)">' + rst["Name"] + stars +'</a></li>')		


			}	
		}
			
		 function refreshAll(){
	        $.getJSON(mbServer + "Startup?callback=foo",
	        function(data){
	          if(data.Id){
	          	addItem(data, true);
	          	loopNextFolder();
	          } else {
	            alert("Error Contacting mbServer");
	          }
	        }
	      );   
	   }
	   
	   function refreshOne(GUID) {
	   	$("#info").html('Refreshing Single Entrypoint');
	   	$("#homeCategories").remove();
			queryNextFolder(GUID);
	   }
	   
		 function queryNextFolder(GUID){
		 	
	   	db.transaction(function(tx) {
		  	tx.executeSql('DELETE FROM mbItems WHERE parent = ?', [GUID], function (tx, results) {
			    console.log('Deleted ' + GUID);
			  }, function (tx, err) {
			  	console.log('Error deleting');
			  });
	   	});
	   	
	      $.getJSON(mbServer + "collection?id="+GUID+"&callback=foo",
        function(data){
          if(data.Id){
          	addItem(data);
						loopNextFolder();
          } else {
            alert("Error Loading");
          }
        });   
	   }
	   
	   function loopNextFolder() {
	      db.transaction(function(tx) {
	      	var GUID = ""
	      	tx.executeSql( 'Select * FROM mbItems WHERE (TypeName = "Folder" OR TypeName = "Season" or TypeName = "Root" or TypeName = "Series") and chk = 0 LIMIT 10', [], function (tx, rst) {
	      		if (rst.rows.length > 0) { 
	      			var GUID = rst.rows.item(0).GUID;
	      			console.log("Working on:" + GUID);
	      			$("#info").html("Getting Folder: " + rst.rows.item(0).Name);
						  if (GUID != "") {
								tx.executeSql('UPDATE mbItems SET chk = 1 WHERE GUID = ?', [GUID], function (tx, rst) {
				      				console.log("Marked");
				      				queryNextFolder(GUID);
				    		}, function (tx, err) {
							  	console.log(err.message);
							  });			  	
						  } else {
						  	showRoot();
						  }
	      		} else {	      			
	      			showRoot();
	      		}
	    		}, function (tx, err) {
				  	console.log(err.message);
				  });
	      });  	
	   }
	   
	   
			function addItem(data, Root) {
				
				db.transaction(function(tx) {
						
            for (var i=0;i<data.Children.length;i++) {

					   var itemArr = { 'GUID': data.Children[i].Id,  'Type': data.Children[i].Type,  'TypeName': '',  'Name': data.Children[i].Name,  'DT': data.Children[i].DateCreated,  'Parent': data.Id };
					   
					   if (Root == true) {
					   	itemArr["TypeName"] = "Root"
					   	itemArr["Parent"] = "home"
					   } else {
			
					   	switch ( itemArr["Type"] ) {
					   		case 1:
					   			itemArr["TypeName"] = "Movie";
					   			break;
					   		case 2:
					   			itemArr["TypeName"] = "Folder";
					   			break;
					   		case 3:
					   			itemArr["TypeName"] = "Folder";
					   			break;
					   		case 4:
					   			itemArr["TypeName"] = "Season";
					   			break;
					   		case 5:
					   			itemArr["TypeName"] = "Episode";
					   			var num1 = itemArr["Name"].substr(0,1);
					   			var num2 = itemArr["Name"].substr(1,1);
					   			if ( isNumeric(num1) == true && num2 == " "  ) {
					   				itemArr["Name"] = "0" + itemArr["Name"];
					   			}
					   			break;
					   		default:
					   			itemArr["TypeName"] = "Song";
					   			break;
					   	}	
					   }
							
					  	tx.executeSql('INSERT INTO mbItems (GUID, Type, TypeName, Name, DT, Parent, chk, Total) VALUES (?, ?, ?, ?, ?, ?, 0, 0)', [ itemArr["GUID"], itemArr["Type"], itemArr["TypeName"], itemArr["Name"], itemArr["DT"], itemArr["Parent"] ], function (tx, results) {
						    console.log('Row inserted');
						    return true;
						  }, function (tx, err) {
						  	console.log('Item Already Exists Error: ' + err.message);
						  	return false;
						  });
						 console.log(Date() + " Added Row")
						}
				 });
			}
	   
			function addItemMeta(data, ParentGUID) {
				db.transaction(function(tx) {
					   var itemArr = { 'GUID': data.Id,  'Overview': data.Overview,  'CustomRating': data.CustomRating,  'DateCreated': data.DateCreated,  'DateModified': data.DateModified, 'ImdbRating': data.ImdbRating,  'ProductionYear': data.ProductionYear,  'RunningTime': data.RunningTime, 'Parent': ParentGUID };
					  	tx.executeSql('INSERT INTO mbMeta (GUID, CustomRating, DateCreated, DateModified, ImdbRating, Overview, ProductionYear, RunningTime, Parent, chk) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)', [ itemArr["GUID"], itemArr["CustomRating"], itemArr["DateCreated"], itemArr["DateModified"], itemArr["ImdbRating"], itemArr["Overview"], itemArr["ProductionYear"], itemArr["RunningTime"], itemArr["Parent"]  ], function (tx, results) {
						    console.log('Row inserted');
						    return true;
						  }, function (tx, err) {
						  	console.log('Item Exists ' +  itemArr["Name"] + ': ' + err.message);
						  	return false;
						  });
						 console.log(Date() + " Added Meta Row")
				 });
			}
			
		 function clearContent() {
				//$("#results").html('');
		 }
		 

		
		function get(url) {
		  try {
		    var xhr = new XMLHttpRequest();
		    xhr.open('GET', url, false);
		    xhr.send();
		    return eval("("+xhr.responseText+")") ;
		  } catch (e) {
		    return ''; // turn all errors into empty results
		  }
		}
		

		
		function slideload(div) {
			if ($("#curPage").val() == "") {
				$("#curPage").val( $(".current:first").attr("id") );
			}
			$("#"+div).attr('class','current');
    	$("#"+div).bind('webkitAnimationEnd', function(e, info){
    		var oldDiv = $("#curPage").val();
    		$("#"+div).attr('class','current');
    		$("#"+oldDiv).attr('class','selectable');
    	});	
			$("#"+div).addClass("slideup");
		}
			
		function clearSearch() {
			$('#searchbox').val('');
			$('#resultssearch').html('');
		}
		
		function fixfuckups(oldDiv, div) {
  		$("#"+div).attr('class','current');
  		$("#"+oldDiv).attr('class','selectable');	
  		
			fuckups = $("#body > div.current");
			if (fuckups.size() > 1) {
				fuckups.attr("class", "selectable");
				$("#home").attr("class", "current");
			}
		}
		
		function flipload(div) {
			if (div == "remote" && online == false) {
				alert("This cannot work in offline mode");
				return false;
			}
			oldDiv = "home";   	
			$("#curHistory").val("");
    	$("#"+div).bind('webkitAnimationEnd', function(e, info){
    		$("#"+div).attr('class','current');
    		$("#"+oldDiv).attr('class','selectable');	
    	});	
    	$("#"+div).attr('class','divFlipIn');
    	$("#"+oldDiv).addClass("divFlipOut");
    	
    	if (div == "remote") {
				NPDuration = 0;
				NPElapsed = 0;
				$("#RemoteTitle").html("Remote");
				$("#RemoteTitle").attr("style", "");
				$("#timespanleft").html("0:00");
				$("#timespanright").html("0:00");
				$("#seekto").attr("style", "");
				$("#sliderh").attr("style", "");
    		NP = setInterval("queryNP()", 3000);
    	}    	
		}
		
		function closeFlip(div) {
			
			oldDiv = "home" 
			$("#curHistory").val("");
			if (div == "search") {
				$("#body > div").each(function(i) {
					if ( $(this).attr("divType") == "New") {
						$(this).remove();	
					}
				});
			}
			
			$("#"+oldDiv).attr('class','current');
    	$("#"+div).bind('webkitAnimationEnd', function(e, info){
    		$("#"+oldDiv).attr('class','current');
    		$("#"+div).attr('class','selectable');	
    		scrollTo(0,0);
    	});	
    	$("#"+div).attr('class','divFlipOut');
    	$("#"+oldDiv).addClass("divFlipIn");
    	
			if (div == "remote") {
    		clearInterval ( NP );
    	}
		}
		
		function queryNP() {
			 $.getJSON(mbServer + "nowplaying",
        function(data){
        	try {
	          if(data.Id){
	          	NPDuration = convertTimeSpantoSeconds(data.TotalTime);
	          	NPElapsed = convertTimeSpantoSeconds(data.Elapsed);
	
	          	$("#RemoteTitle").html("Now Playing:<br>" + data.Name)
	          	$("#RemoteTitle").attr("style", "font-size: 0.8em;");
	          	$("#timespanright").html( "-" + hms2(NPDuration-NPElapsed) );
	          	$("#timespanleft").html( hms2(NPElapsed) );
	          	
	          	var max = $("#sliderbar").width();
	          	var sh = (NPElapsed/NPDuration);
	          	x = max*sh;
	          	$("#seekto").attr("style", "left: " + (x-10) + "px");
							$("#sliderh").attr("style", "width: " + (sh*100) + "%") ;			    
	          }
        	} catch (E) {;}
        });
		}
		
		function convertTimeSpantoSeconds(str) {
			arr = str.split(":");
			var seconds = 0;

			if (arr.length == 3) {
				seconds = seconds + ((arr[0]*60)*60);
				seconds = seconds + (arr[1]*60);
				seconds = seconds + (arr[2]*1);
			}
						
			return seconds;
		}
		
		function hms2(totalSec) {
			hours = parseInt( totalSec / 3600 ) % 24;
			minutes = parseInt( totalSec / 60 ) % 60;
			seconds = totalSec % 60;
			return hours + ":" + (minutes < 10 ? "0" + minutes : minutes) ;
		}
		
		function closeSlide(div) {
			var oldDiv = $("#curPage").val();
			$("#"+oldDiv).attr('class','current');
    	$("#"+div).bind('webkitAnimationEnd', function(e, info){
    		$("#"+oldDiv).attr('class','current');
    		$("#"+div).attr('class','selectable');
    	});  	
			$("#"+div).addClass("slidedown");
		}
		
		function saveSettings() {
			try {
				localStorage.removeItem("Sort");
				localStorage.removeItem("snapTo");
				localStorage.removeItem("perPage");
				localStorage.removeItem("imdb");
				localStorage.removeItem("StartupScan");
				
				localStorage.setItem("Sort", $("#Sort").val() );
				localStorage.setItem("snapTo", $('#snapTo').attr('checked'));
				localStorage.setItem("perPage", $("#perPage").val() );  
	  		localStorage.setItem("imdb", $('#imdb').attr('checked') );
				localStorage.setItem("StartupScan", $('#StartupScan').attr('checked') );
			} catch (E) {;}
			closeSlide('config');
			
		}
		
		function loadSettings() {
			
			$("#curPage").val("");
			
  		if (localStorage.getItem("Sort") == null) {
  			localStorage.setItem("Sort", "Name ASC");
  			localStorage.setItem("StartupScan", "true");
  			localStorage.setItem("imdb", "true");
  			localStorage.setItem("snapTo", "true");
  			localStorage.setItem("perPage", "40");  			
  			alert("Add this page to your home screen to view the custom icon, startup screen, and full screen mode.");
  		}
  		
  		$("#Sort").val( localStorage.getItem("Sort") );
  		$("#perPage").val( localStorage.getItem("perPage") );
  		if (localStorage.getItem("imdb")=="true") {
  			document.getElementById("imdb").checked = true;
  		} else {
  			document.getElementById("imdb").checked = false;
  		}
  		if (localStorage.getItem("snapTo")=="true") {
  			document.getElementById("snapTo").checked = true;
  		} else {
  			document.getElementById("snapTo").checked = false;
  		}
  		if (localStorage.getItem("StartupScan")=="true") {
  			document.getElementById("StartupScan").checked = true;
  		} else {
  			document.getElementById("StartupScan").checked = false;
  		}
  		
		}
		
		function doRemote(action, ele, btype) {
			/*
			if (btype=="sq") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 7px; background-color: rgba(41, 141, 218, 0.7);");
			}
			if (btype=="bcr") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 40px; background-color: rgba(41, 141, 218, 0.7);");
			}
			if (btype=="scr") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 40px; background-color: rgba(41, 141, 218, 0.7); color: rgba(41, 141, 218, 1);");
			}
			if (btype=="blnk") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 7px; background-color: rgba(41, 141, 218, 0.7); color: rgba(41, 141, 218, 1);");
			}
			
			window.setTimeout(function() {
				$("#"+ele).attr("style", "");
			}, 500);
			*/
			
			data = get(mbServer + "command?type="+action+"&callback=foo");
		}
		
		function doPage(action, ele, btype) {
			if (btype=="sq") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 7px; background-color: rgba(41, 141, 218, 0.7);");
			}
			if (btype=="bcr") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 40px; background-color: rgba(41, 141, 218, 0.7);");
			}
			if (btype=="scr") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 40px; background-color: rgba(41, 141, 218, 0.7); color: rgba(41, 141, 218, 1);");
			}
			if (btype=="blnk") {
				$("#"+ele).attr("style", "-webkit-box-shadow:0 2px 6px rgba(41, 141, 218, 0.7); border-radius: 7px; background-color: rgba(41, 141, 218, 0.7); color: rgba(41, 141, 218, 1);");
			}
			
			data = get(mbServer + "screen?type="+action+"&callback=foo");
			window.setTimeout(function() {
				$("#"+ele).attr("style", "");
			}, 500);
		}
		
		function isNumeric(input)	{
		   return (input - 0) == input && input.length > 0;
		}
		
		function getTrailer(GUID, bkdrop) {
			data = get(mbServer + "trailers?id="+GUID+"&callback=foo");
	    if(data) {
        for (var i=0;i<data.length;i++) {
					if (data[i].format == "H.264") {
						console.log("trailer found");
						var video = document.createElement("video");
						video.setAttribute("src", data[i].url);
						video.setAttribute("height", "300px");
						video.setAttribute("width", "100%");
						video.setAttribute("preload", "none");
						video.setAttribute("autoplay", "false");
						video.setAttribute("poster", mbServer + '/directimage/?id='+bkdrop+'&imagetype=BackdropImage&maxwidth=300');
						video.setAttribute("controls", "");
						$('#backdrop'+ GUID).html("");
						$('#backdrop'+ GUID).append(video);
						//$("#playcontrols").append("<a class='watchVideo' href=\"javascript:doTrailer('"+escape(GUID)+"')\">Play Trailer</a>");
						
						
						break;
					}
				}
	    }
		}
		
		function doTrailer(url) {
			$.post(mbServer + "playtrailer", { trailer: url } );
		}

		
/** OFFLINE CACHING **/

(function(){
	var webappCache = window.applicationCache;
	
	function loaded()
	{
		
		switch(webappCache.status)
		{
			case 0:
				console.log("Cache status: Uncached");
				break;
			case 1:
				console.log("Cache status: Idle");
				break;
			case 2:
				console.log("Cache status: Checking");
				break;
			case 3:
				console.log("Cache status: Downloading");
				break;
			case 4:
				console.log("Cache status: Updateready");
				break;
			case 5:
				console.log("Cache status: Obsolete");
				break;
		}
	}
	function updateCache()
	{
		webappCache.swapCache();
		console.log("Cache has been updated due to a change found in the manifest");
	}
	function errorCache()
	{
		console.log("You're either offline or something has gone horribly wrong.");
	}

	window.addEventListener("load", loaded, false);
	webappCache.addEventListener("updateready", updateCache, false);
	webappCache.addEventListener("error", errorCache, false);
})();

/** END OFFLINE CACHING **/
